package com.gonsin.ta.example.controllers;

import com.gonsin.ta.logic.TA;
import com.gonsin.ta.logic.enums.TaResult;
import com.gonsin.ta.logic.process.TaResponse;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/test")
@RestController
@Slf4j
public class ExampleController {

    /**
     * 运行一个预约的例子
     */
    @GetMapping("/commit")
    public String testCommit(){
        TaResponse response = TA.ready("预约会议")
                .put("value1", "上下文内容")
                .put("AUDIT_TIMEOUT", 1)
                .go();

        // 如果碰到了等待节点，则根据自身的业务代码，由其他
        if(response.getResult() == TaResult.WAITING){
//            log.info("流程实例【{}】正在等待信号【{}】", response.getInstanceId(), response.getWaitingSignal());
            return "ok";
        }

        if(response.getResult() == TaResult.FINISHED){
//            log.info("流程实例【{}】执行完毕", response.getInstanceId());
            return "ok";
        }
        return "ok";
    }

    /**
     * 发送信号，控制流程走向
     */
    @GetMapping("/signal")
    public String testCommit(
            @ApiParam("是否通过预约") @RequestParam("apply") boolean apply,
            @ApiParam("信号值") @RequestParam("signal") String signal,
            @RequestParam("实例id") String instanceId){

        TaResponse response = TA.signal(instanceId, signal)
                .put("apply", apply)
                .post();

        // 如果碰到了等待节点，则根据自身的业务代码，由其他
        if(response.getResult() == TaResult.WAITING){
            log.info("流程实例【{}】正在等待信号【{}】", response.getInstanceId(), response.getContext().getWaitingSignal());
            return "ok";
        }

        // 如果碰到了等待节点，则根据自身的业务代码，由其他
        if(response.getResult() == TaResult.FINISHED){
            log.info("流程实例【{}】执行完毕", response.getInstanceId());
            return "ok";
        }
        return "ok";
    }

    /**
     * 运行一个可以自动结束的例子
     */
    @GetMapping("endable")
    public String testEnd(){
        TA.ready("节点结束").go();
        return "ok";
    }

}
